//
//  TCollectionViewControllelr.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/8.
//  Copyright © 2019 李文强. All rights reserved.
//

#import "TCollectionViewControllelr.h"
#import "SYRequestAPI+Teach.h"
#define CellSP 20*fw
#define CellW 50*fw


#import "KeChengNectVC.h"
#import "TeacherClassListModel.h"
#import "KeChengWeiShangKeShiModel.h"
#import "KeChengYiShangKeShiModel.h"
//已上课时
#import "JiaoXueYiShangKeShiNextVC.h"
#import "SYKCNotClassCollectionViewCell.h"


@interface TCollectionViewControllelr ()<TeachTopSelectedDelegate>
{
    BOOL Type;
    NSString *tableName;
    int viewType;
    
    NSString * cellType;
    CJClassSelectedView *classView;
    TeacherClassListModel *mainClassModel;
    NSString *getParamaOfDate;//全局时间搜索字段
}
//课程点击cell的下级界面
@property (nonatomic, strong) KeChengNectVC *keChengListContendView;
//已上课时
@property (nonatomic, strong) JiaoXueYiShangKeShiNextVC *yiShangKeShiView;
//教师班级数组
@property (nonatomic, strong) NSMutableArray *classDataArray;
@property (nonatomic, strong) NSMutableArray *weiShangKeShiArray;//未上课时
@property (nonatomic, strong) NSMutableArray *yiShangKeShiArray;//已上课时
@end

@implementation TCollectionViewControllelr

static NSString * const reuseIdentifier = @"Cell";
- (TeachTopSelectedView *)topSelectView{
    if (!_topSelectView) {
        TeachTopSelectedView *topView = [[TeachTopSelectedView alloc]init];
        topView.frame = CGRectMake(0, 0, 875*fw, 44);
        topView.delegate = self;
        _topSelectView = topView;
    }
    return _topSelectView;
}


- (UILabel *)noDataLabel{
    if (!_noDataLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.text = @"当前数据为空";
        label.textAlignment = 1;
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(getDataAgin:)];
        [label addGestureRecognizer:tap];
        _noDataLabel = label;
    }
    return _noDataLabel;
}
#pragma mark - 默认显示的班级
- (void)defalutClassID{
//     NSMutableArray *array = [PublickFunctionObject getArrayForDataForKey:ClassListOfTeacherDefalut];
//    TeacherClassListModel *model = [TeacherClassListModel yy_modelWithJSON:array[0]];
//    mainClassModel = model;
    [self getWeiShangKeShiRequest:getParamaOfDate];
   
}
- (void)getDataAgin:(UIButton *)sender{
    [self getWeiShangKeShiRequest:self->getParamaOfDate];
    [self getYiShangKeShiRequest:self->getParamaOfDate];
    
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _classDataArray = [NSMutableArray new];
    _weiShangKeShiArray = [NSMutableArray new];
    _yiShangKeShiArray = [NSMutableArray new];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showView) name:@"ShowView" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(weiShangKeShi:) name:@"WeiShangKeShiNotice" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(yiShangKeShi:) name:@"YiShangKeShiNotice" object:nil];
    [self.collectionView headerRefreshBlock:^{
        [self->_weiShangKeShiArray removeAllObjects];
        [self->_yiShangKeShiArray removeAllObjects];
        [self getWeiShangKeShiRequest:self->getParamaOfDate];
        [self getYiShangKeShiRequest:self->getParamaOfDate];
        
    }];
    
//    [self.collectionView fooderRefreshBlock:^{
//        
//    }];
}
- (void)initSubView{
    Type = YES;
    cellType = @"未上课时";
    getParamaOfDate = @"";
    self.view.backgroundColor = MAINBACKCOLOR;
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
//    [self.collectionView registerClass:[TCollectionViewCell class] forCellWithReuseIdentifier:@"TCollectionViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"SYKCNotClassCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"SYKCNotClassCollectionViewCell"];
    
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeView:) name:@"ChangeCellSpaNotice" object:nil];
    // Do any additional setup after loading the view.
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.top.equalTo(@44);
        make.right.equalTo(@0);
        make.bottom.equalTo(@0).offset(-20);
    }];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.topSelectView];
    [self.topSelectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@0);
        make.height.equalTo(@44);
    }];
    
    [self.view addSubview:self.noDataLabel];
    [_noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@44);
        make.bottom.equalTo(@0);
    }];
    
    mainClassModel = [TeacherClassListModel new];
    [self defalutClassID];
}
- (void)weiShangKeShi:(NSNotification *)info{
    cellType = @"未上课时";
    [self.collectionView reloadData];
    if (self->_weiShangKeShiArray.count == 0) {
        self->_noDataLabel.hidden = NO;
    }else{
        self->_noDataLabel.hidden = YES;
    }
    [self.collectionView reloadData];
}
- (void)yiShangKeShi:(NSNotification *)info{
    cellType = @"已上课时";
    [self.collectionView reloadData];
    if (_yiShangKeShiArray.count == 0) {
        [MBProgressHUD mj_hideHUD];
        [self getYiShangKeShiRequest:getParamaOfDate];
        
        self->_noDataLabel.hidden = NO;
    }else{
        self->_noDataLabel.hidden = YES;
        [self.collectionView reloadData];
    }
}
- (void)showView{
    self.collectionView.hidden = NO;
}
- (void)changeView:(NSNotification *)info{
    BOOL type = [[info.userInfo objectForKey:@"Type"] intValue];
    if (type == YES) {
        Type = NO;
    }else{
        Type = YES;
    }
    [self.collectionView reloadData];
}
- (void)leftButtonClick{
    __block TCollectionViewControllelr *mySelf = self;
    [CJYearMonthSelectedView showDatePickerWithTitle:@"选择月份" minDateStr:@"2000-10" resultBlock:^(NSString *selectValue) {
        //选择完成后的操作
        if ([selectValue isEqualToString:@"全部"]) {
            selectValue = @"";
            mySelf.topSelectView.timeButton.bottomLabel.text = @"全部";
        } else {
            NSArray *array = [selectValue componentsSeparatedByString:@"-"];
            mySelf.topSelectView.timeButton.bottomLabel.text = [NSString stringWithFormat:@"%@年%@月",array[0],array[1]];
        }
        
        self->getParamaOfDate = selectValue;
      //  NSLog(@"selected month is %@", selectValue);
        if ([self->cellType isEqualToString:@"已上课时"]) {
            [self->_yiShangKeShiArray removeAllObjects];
            [mySelf getYiShangKeShiRequest:self->getParamaOfDate];
        }else{
            [self->_weiShangKeShiArray removeAllObjects];
            [mySelf getWeiShangKeShiRequest:self->getParamaOfDate];
        }
        
    }];
}
#pragma mark - 课程未上课时
- (void)rightButtonClick{
    __block TCollectionViewControllelr *mySelf = self;
    [CJClassSelectedView showDatePickerWithTitle:@"选择班级" minDateStr:@"年级一" resultBlock:^(TeacherClassListModel * _Nonnull selectValue) {
       // NSLog(@"输出选择的班级 %@",selectValue);
        self->mainClassModel = selectValue;
         mySelf.topSelectView.nianjiButton.bottomLabel.text = selectValue.name;
        if ([self->cellType isEqualToString:@"已上课时"]) {
            [mySelf getYiShangKeShiRequest:self->getParamaOfDate];
        }else{
            [mySelf getWeiShangKeShiRequest:self->getParamaOfDate];
        }
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //课程
    if ([cellType isEqualToString:@"已上课时"]) {
        return _yiShangKeShiArray.count;
    }else{
        return _weiShangKeShiArray.count;
    }
    
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SYKCNotClassCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SYKCNotClassCollectionViewCell" forIndexPath:indexPath];
 if ([cellType isEqualToString:@"已上课时"]) {

     KeChengYiShangKeShiModel *model = _yiShangKeShiArray[indexPath.row];
     [cell transferDataKeChengModel:model keChengWeiModel:[KeChengWeiShangKeShiModel alloc] cellType:cellType];
     
     
     
 }else if ([cellType isEqualToString:@"未上课时"]){
      __weak typeof(self) weakSelf = self;
    
     
     KeChengWeiShangKeShiModel *model = _weiShangKeShiArray[indexPath.row];
     [cell transferDataKeChengModel:[KeChengYiShangKeShiModel alloc] keChengWeiModel:model cellType:cellType];
     cell.block = ^(NSInteger index) {
         [weakSelf selectLookBtnIndex:index wskModel:model];
     };
 }
        
    return cell;
}
- (void)selectLookBtnIndex:(NSInteger)index wskModel:(KeChengWeiShangKeShiModel *)wsk {
    if (index == 0) {//申请
        [self postResourceApplyAttendProgressId:wsk.attendProgressId];
    } else if (index == 1) { //查看
        _keChengListContendView = [[KeChengNectVC alloc]initWithClassID:wsk.classId andLessonID:wsk.lessonId attendProgressId:wsk.attendProgressId];
        _keChengListContendView.view.backgroundColor = [UIColor whiteColor];
        _keChengListContendView.isSelect = YES;
        _keChengListContendView.wsksModel = wsk;
        [self.view addSubview:_keChengListContendView.view];
        
        [_keChengListContendView.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.right.equalTo(@0);
            make.top.equalTo(@0);
            make.height.equalTo(@0).offset(APP_HEIGHT);
        }];
    }
}


#pragma mark == collectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(204*fw, 105*fh);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
//top, left, bottom, right
    if (Type == YES) {
        return UIEdgeInsetsMake(CellSP, CellSP, CellSP,CellSP);
    }else{
        return UIEdgeInsetsMake(CellSP, CellW, CellSP,CellW);
    }
    
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return CellSP;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return CellSP;
}

//是否允许移动Item
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0)
{
    return YES;
}
//移动Item时触发的方法
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0);
{
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    [MBProgressHUD mj_showMessage:nil toView:self.collectionView];
    if ([cellType isEqualToString:@"已上课时"]) {
        //课程
        KeChengYiShangKeShiModel *model = _yiShangKeShiArray[indexPath.row];
        _yiShangKeShiView = [[JiaoXueYiShangKeShiNextVC alloc]initWithClassID:model.classId andLessonID:model.lessonId];
        _yiShangKeShiView.view.backgroundColor = MAINBACKCOLOR;
        [self.view addSubview:_yiShangKeShiView.view];
        [_yiShangKeShiView.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.right.equalTo(@0);
            make.top.equalTo(@0);
            make.height.equalTo(@0).offset(APP_HEIGHT);
        }];
//        [UIView animateWithDuration:0.5 animations:^{
//            self->_yiShangKeShiView.view.frame = CGRectMake(0, 0, self.view.frame.size.width, APP_HEIGHT);
//        } completion:^(BOOL finished) {
//            [MBProgressHUD mj_hideHUDForView:self.collectionView];
            
//        }];
    }else if ([cellType isEqualToString:@"未上课时"]){
        //课程
        KeChengWeiShangKeShiModel *model = _weiShangKeShiArray[indexPath.row];
        _keChengListContendView = [[KeChengNectVC alloc]initWithClassID:model.classId andLessonID:model.lessonId attendProgressId:model.attendProgressId];
        _keChengListContendView.view.backgroundColor = [UIColor whiteColor];
        _keChengListContendView.wsksModel = model;
        [self.view addSubview:_keChengListContendView.view];
        [_keChengListContendView.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.right.equalTo(@0);
            make.top.equalTo(@0);
            make.height.equalTo(@0).offset(APP_HEIGHT);
        }];
//        _keChengListContendView.view.frame = CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, APP_HEIGHT);
//        [UIView animateWithDuration:0.5 animations:^{
//            self->_keChengListContendView.view.frame = CGRectMake(0, 0, self.view.frame.size.width, APP_HEIGHT);
//        } completion:^(BOOL finished) {
//            [MBProgressHUD mj_hideHUDForView:self.collectionView];
//        }];
    }

    [PublickFunctionObject changeMainView:@"TeachChangeNotice" AndType:Type];
    
}
#pragma mark <UICollectionViewDelegate>

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}

// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
- (void)getDataForView:(NSString *)name{
    tableName = name;
    [self.collectionView reloadData];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"ShowView" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"WeiShangKeShiNotice" object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"YiShangKeShiNotice" object:nil];
}
#pragma mark - 课程-未上课时
- (void)getWeiShangKeShiRequest:(NSString *)date{
    if (date.length == 0) {
        date = @"";
    }
    if (mainClassModel.id.length == 0) {
        mainClassModel = [TeacherClassListModel new];
        mainClassModel.id = @"0";
    }
    NSDictionary *parama = @{@"classId":mainClassModel.id,
                             @"date":date};
//    [MBProgressHUD mj_showMessage:nil toView:self.collectionView];
//    [MBProgressHUD mj_showLoading];
   // NSLog(@"未上课时参数 %@",parama);
    [SYRequestAPI sy_getUnAttend:parama success:^(id  _Nonnull responseObject) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        [self->_weiShangKeShiArray removeAllObjects];
      //  NSLog(@"得到课程-未上课时数据 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            KeChengWeiShangKeShiModel *model = [KeChengWeiShangKeShiModel yy_modelWithJSON:dic];
            [self->_weiShangKeShiArray addObject:model];
        }
        if (self->_weiShangKeShiArray.count == 0) {
            self->_noDataLabel.hidden = NO;
        }else{
            self->_noDataLabel.hidden = YES;
        }
//        [MBProgressHUD mj_hideHUDForView:self.collectionView];
        [MBProgressHUD mj_hideHUD];
        [self.collectionView reloadData];
    } fail:^(NSError *error) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
//        [MBProgressHUD mj_hideHUDForView:self.collectionView];
        [MBProgressHUD mj_hideHUD];
        [XSInfoView showInfo:error.message onView:self];
    }];
}
#pragma mark - 课程-已上课时
- (void)getYiShangKeShiRequest:(NSString *)date{
    if (mainClassModel.id.length == 0) {
        mainClassModel = [TeacherClassListModel new];
        mainClassModel.id = @"0";
    }
    NSDictionary *parama = @{@"classId":mainClassModel.id,
                             @"date":date};
   // NSLog(@"已上课时参数 %@",parama);
    [MBProgressHUD mj_showMessage:nil toView:self.collectionView];
    [SYRequestAPI sy_getAttend:parama success:^(id  _Nonnull responseObject) {
        //NSLog(@"得到课程-已上课时数据 %@",responseObject);
        NSArray *array = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            KeChengYiShangKeShiModel *model = [KeChengYiShangKeShiModel yy_modelWithJSON:dic];
            [self->_yiShangKeShiArray addObject:model];
        }
        if (self->_yiShangKeShiArray.count == 0) {
            self->_noDataLabel.hidden = NO;
        }else{
            self->_noDataLabel.hidden = YES;
        }
        [MBProgressHUD mj_hideHUDForView:self.collectionView];
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self.collectionView];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}

- (void)postResourceApplyAttendProgressId:(NSString *)progressid {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"请输入申请原因" preferredStyle:UIAlertControllerStyleAlert];
    //增加取消按钮；
      [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    //增加确定按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      //获取第1个输入框；
      UITextField *userNameTextField = alertController.textFields.firstObject;
        NSLog(@"------%@---",userNameTextField.text);
        if (userNameTextField.text.length > 0) {
            [MBProgressHUD mj_showLoading];
            [SYRequestAPI sy_postResourceApplyGroupId:@"" campusId:@"" attendProgressId:progressid lessonId:@"" applyReason:userNameTextField.text success:^(BOOL isSuccess) {
                [MBProgressHUD mj_hideHUD];
                [MBProgressHUD zr_showError:@"申请成功，等待资源下发"];
            } fail:^(NSError *error) {
                [MBProgressHUD mj_hideHUD];
                [MBProgressHUD zr_showError:error.domain];
            }];
        } else {
            [NSObject executeRunloop:^{
                [MBProgressHUD zr_showError:@"请输入申请原因"];
            } afterDelay:0.5];
            
        }
      
    }]];
    
    //定义第一个输入框；
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
      textField.placeholder = @"请输入申请原因";
    }];
    
    [self presentViewController:alertController animated:true completion:nil];
    
    
    
}

@end
